package com.qhhc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qhhc.entity.CarPhoto;
import com.qhhc.mapper.CarPhotoMapper;
import com.qhhc.service.CarPhotoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CarPhotoServiceImpl extends ServiceImpl<CarPhotoMapper, CarPhoto> implements CarPhotoService {

    @Override
    public List<CarPhoto> getPhotosByCarId(Long carId) {
        LambdaQueryWrapper<CarPhoto> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CarPhoto::getCarId, carId)
               .orderByAsc(CarPhoto::getSortOrder);
        return list(wrapper);
    }

    @Override
    @Transactional
    public boolean setMainPhoto(Long photoId, Long carId) {
        // First, set all photos of this car to non-main
        LambdaQueryWrapper<CarPhoto> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CarPhoto::getCarId, carId);
        CarPhoto updatePhoto = new CarPhoto();
        updatePhoto.setIsMain(false);
        update(updatePhoto, wrapper);

        // Then set the selected photo as main
        CarPhoto mainPhoto = new CarPhoto();
        mainPhoto.setPhotoId(photoId);
        mainPhoto.setIsMain(true);
        return updateById(mainPhoto);
    }

    @Override
    public boolean deletePhoto(Long photoId) {
        return removeById(photoId);
    }

    @Override
    public boolean updatePhotoSort(Long photoId, Integer sortOrder) {
        CarPhoto photo = new CarPhoto();
        photo.setPhotoId(photoId);
        photo.setSortOrder(sortOrder);
        return updateById(photo);
    }

    @Override
    public List<CarPhoto> getAllMainPhoto() {
        LambdaQueryWrapper<CarPhoto> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CarPhoto::getIsMain, 1)
                .orderByAsc(CarPhoto::getSortOrder);
        return list(wrapper);
    }
} 